/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package es.overtime.sqltools.db;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

/**
 *
 * @author pbarrach
 */
public class ConexionHSQLDB {
    
    private Connection conn = null;
    
    // Nombre de la base de datos
    private static String db_file_name_prefix = "sqltools";
    
    public ConexionHSQLDB(){
        try {
            Class.forName("org.hsqldb.jdbcDriver");            
            conn = DriverManager.getConnection("jdbc:hsqldb:" + db_file_name_prefix, "sa", ""); //BFB2008PBP            
        } catch (Exception ex) {
            
        }    
    }
    
    public ResultSet ejecutaSQL (String sql) throws Exception {
        Statement st = conn.createStatement(); 
        ResultSet result = null;
        
        result = st.executeQuery(sql);
        
        return result;
    }
    
    public int updateSQL (String sql) throws Exception {
        Statement st = conn.createStatement(); 
        int result = -1;
        
        result = st.executeUpdate(sql);
        
        return result;
    }
    
    public void CerrarConexion()  {
        try {
            Statement st = conn.createStatement();       
            st.execute("SHUTDOWN");
        } catch (Exception ex) {
            
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (Exception exSQL) {
                    
                }
            }                
        }   
    }
    

    
    public boolean existeTabla(String tabla) throws Exception {
        String tipos[] = new String[1];   // Listamos sólo tablas
        tipos[0] = "TABLE";
        boolean existe = false;
        
        DatabaseMetaData metadata = conn.getMetaData();
        
        ResultSet rsTablas = metadata.getTables(null, null, "%" , tipos); // devuelve todas las tablas
        
        while (rsTablas.next()) {
            if(rsTablas.getString("TABLE_NAME").equalsIgnoreCase(tabla)) {
                existe = true;
                rsTablas.last();
            }            

        }
        rsTablas.close();
        
        return existe;
    }
    
}
